<template>
  <el-container>
    <basic-crud ref="crudRef" :defaultListParams="{orderBy:'needEndDate',orderMethod:'asc'}" :option="option"
                apiGetListUrl="/mes/mesWorkOrderController/listHasCompleteCount" selectType="multiple"
                :fastSearch="{name:'计划编号、规程编号、项目号',fastColumn:'sourceCode,primaryTargetCode,code'}"
                @selection-change="handleChangeSelect">
      <template #showLevel="{row}">
        <el-tooltip v-if="row.showLevel == 1" class="item" content="已经超期了" effect="dark" placement="top-start">
          <el-icon :size="20" color="red">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 2" class="item" content="剩余交付时间5天内" effect="dark"
                    placement="top-start">
          <el-icon :size="20" color="orange">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 3" class="item" content="剩余交付时间5到10天内" effect="dark"
                    placement="top-start">
          <el-icon :size="20" color="yellow">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 4" class="item" content="交付日期可控" effect="dark" placement="top-start">
          <el-icon :size="20" color="green">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 5" class="item" content="还未派工" effect="dark" placement="top-start">
          <el-icon :size="20" color="gray">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
        <el-tooltip v-else-if="row.showLevel == 6" class="item" content="已经入库" effect="dark" placement="top-start">
          <el-icon :size="20" color="lightgreen">
            <BellFilled/>
          </el-icon>
        </el-tooltip>
      </template>
      <template #percent="{row}">
        <el-progress :format="formatPercent" :percentage="row.percent" :stroke-width="15" text-inside></el-progress>
      </template>
      <template #menu-left>
        <el-button v-permission="'productionPlan-ERPADDPLAN'" :loading="loadingBtn.eprAddPlanLoading" icon="plus"
                   type="primary" @click="erpAddClickHandler">
          ERP新增计划
        </el-button>
        <el-button v-permission="'productionPlan-MANUALADDPLAN'" :loading="loadingBtn.manualAddPlanLoading" icon="plus"
                   type="primary"
                   @click="erpHandClickHandler"> 手动新增计划
        </el-button>
        <el-button v-permission="'productionPlan-SETSPECIFICATION'" :loading="loadingBtn.setSpecificationLoading"
                   icon="Setting" plain type="primary"
                   @click="addByWorkHandler"> 设置规程
        </el-button>
        <el-button v-permission="'productionPlan-SETASSIGNER'" :loading="loadingBtn.setAssignerLoading" icon="user"
                   plain type="success"
                   @click="setAssignerHandler"> 产品主管
        </el-button>
        <el-button v-permission="'productionPlan-EXPORTMONTH'" :loading="loadingBtn.exportMonthLoading"
                   icon="FolderChecked" plain type="primary"
                   @click="exportMonth"> 导出计划
        </el-button>
        <el-button v-permission="'productionPlan-PRODUCTSADD'" :loading="loadingBtn.productsAddLoading" icon="plus"
                   plain type="primary"
                   @click="productionPlanPushsHandler"> 计划补录
        </el-button>
        <el-button v-permission="'productionPlan-forcedFinishPlan'" :loading="loadingBtn.forcedFinishPlanLoading"
                   icon="Reading" plain type="primary"
                   @click="forcedFinishPlanHandler"> 完成计划
        </el-button>
        <el-button v-permission="'productionPlan-IMPORTFINISHPLAN'" :loading="loadingBtn.importFinishPlanLoading"
                   icon="FolderAdd" plain type="primary"
                   @click="importFinishPlanHandler"> 导入补录计划
        </el-button>
        <el-button v-permission="'productionPlan-ADJUSTMENT'" :loading="loadingBtn.adjustmentAllLoading" icon="Setting"
                   plain type="primary"
                   @click="adjustClickHandler"> 多选调整
        </el-button>
      </template>

      <template #menu="{row}">
        <el-button v-permission="'productionPlan-DELETEROW'" :loading="loadingBtn.deleteRowLoading" icon="Delete" plain
                   style="color: red" type="text"
                   @click="delCrudClickHandler(row)"> 删除
        </el-button>
        <el-button v-permission="'productionPlan-SPECIFICATION'" :loading="loadingBtn.specificationLoading"
                   icon="Setting" plain type="text"
                   @click="regulationAddClickHandler(row)"> 规程
        </el-button>
        <el-button v-permission="'productionPlan-ADJUSTMENT'" :loading="loadingBtn.adjustmentLoading" icon="Setting"
                   plain type="text" @click="lineAdjust(row)">
          调整
        </el-button>
        <el-button v-permission="'productionPlan-onOpenWorksReplace'" :loading="loadingBtn.onOpenWorksReplaceLoading"
                   icon="Sunrise" plain type="text"
                   @click="replaceClickHandler(row)"> 替换
        </el-button>
        <el-button v-if="row.status === 'ExecuteFinish'" v-permission="'productionPlan-WAREHOUSING-WAREHOUSING'"
                   :loading="loadingBtn.warehousingLoading"
                   icon="user" plain style="color:#67C23A;"
                   type="text"
                   @click="openStoreHandler(row)"> 入库
        </el-button>
        <el-button v-permission="'productionPlan-editPlanName'" :disabled="!!row.inputSourceId"
                   :loading="loadingBtn.editPlanNameLoading" icon="EditPen"
                   plain
                   type="text" @click="editPlanNameHandler(row)">
          调整名称
        </el-button>
      </template>
    </basic-crud>
    <!-- ERP新增计划 -->
    <select-request-add ref="SelectRequestAddRef" :submitSuccess="handleRefresh"></select-request-add>
    <!-- 手动新增计划 根据产品新增 -->
    <basic-dialog v-model="SelectRequestAddDialog.visible"
                  :loading="SelectRequestAddDialog.loading"
                  :submitBtnLoading="SelectRequestAddDialog.submitLoading" title="选择产品新增计划" width="1000"
                  @cancel="handleSelectRequestAddCancel"
                  @submit="handleSelectRequestAddSubmit">
      <avue-form ref="formProductRefs" v-model="SelectRequestAddForm" :option="SelectRequestAddFormOption">
        <template #pdmModelName>
          <el-select
              v-model="SelectRequestAddForm.pdmModelName"
              filterable
              placeholder="请输入产品型号"
              @change="gteProduct"
          >
            <el-option
                v-for="item in dicModuName"
                :key="item.code"
                :label="item.code"
                :value="item.code"
            >
            </el-option>
          </el-select>
        </template>
        <template #pdmProductName>
          <el-select
              v-model="SelectRequestAddForm.pdmProductName"
              filterable
              placeholder="请选择产品名称"
          >
            <el-option
                v-for="item in dicProductName"
                :key="item.id"
                :label="`${item.code}#${item.name}`"
                :value="`${item.id}#${item.name}`"
            >
            </el-option>
          </el-select>
        </template>
        <template #files>
          <avue-upload
              v-model="SelectRequestAddForm.files"
              :action="uploadObject.action"
              :headers="uploadObject.headers"
              :propsHttp="uploadObject.propsHttp"
              :upload-after="uploadAfter"
          ></avue-upload>
        </template>
      </avue-form>
    </basic-dialog>
    <!-- 设置规程 -->
    <select-technology ref="SelectTechnologyRef" @refresh="handleRefresh"></select-technology>
    <!-- 设置产品主管 -->
    <BasicCrudUserRefer ref="userProductRef" v-model="userVisible" @submit="handleUserSubmit"></BasicCrudUserRefer>
    <!-- 计划补录 -->
    <basic-dialog v-model="productionPlanPushsDialog.visible"
                  :laoding="productionPlanPushsDialog.loading"
                  :submitBtnLoading="productionPlanPushsDialog.submitLoading"
                  title="计划补录"
                  width="1000"
                  @cancel="handleProductionPlanPushsAddCancel"
                  @submit="handleProductionPlanPushsAddSubmit">
      <avue-form ref="formProductPlanRefs" v-model="productionPlanPushsAddForm"
                 :option="productionPlanPushsAddFormOption">
      </avue-form>
    </basic-dialog>
    <!-- 完成计划 -->
    <basic-dialog
        v-model="forcedFinishPlanDialog.visible"
        title="完成计划"
        width="600px"
        @cancel="forcedFinishPlanDialogCancel"
        @submit="forcedFinishPlanDialogSubmit"
    >
      <basic-containers>
        <avue-form ref="forcedFinishPlanRef" v-model="forcedFinishPlanForm" :option="forcedFinishPlanFormOption"
                   :upload-after="uploadAfter">
        </avue-form>
      </basic-containers>
    </basic-dialog>
    <!-- 导入补录计划 -->
    <improt-file v-model="fileVisible" export-url="/mes/mesWorkOrderController/downloadImportTempFinish"
                 upload-url="/mes/mesWorkOrderController/importDataFinish"></improt-file>
    <!-- 多选调整 -->
    <basic-dialog v-model="adjustDialog.visible" title="计划调整" width="1000"
                  @cancel="handlerAdjustAddCancel"
                  @submit="handlerAdjustAddSubmit">
      <avue-form ref="djustDialogAddRefs" v-model="adjustDialogAddForm"
                 :option="djustDialogAddFormOption">
      </avue-form>
    </basic-dialog>
    <!-- 入库 -->
    <basic-dialog v-model="beStoreDialog.visible" title="入库" width="600"
                  @cancel="beStoreAddCancel"
                  @submit="beStoreAddSubmit">
      <avue-form ref="beStoreAddRefs" v-model="beStoreForm"
                 :option="beStoreFormOption">
      </avue-form>
    </basic-dialog>
    <!-- 替换 -->
    <basic-dialog v-model="replaceDialog.visible" title="计划调整" width="1000"
                  @cancel="handlerReplaceAddCancel"
                  @submit="handlerReplaceAddSubmit">
      <el-container>
        <el-main style="margin-right: 20px">
          <!-- 复用计划调整option配置 -->
          <avue-form ref="replaceDialogAddRefs" v-model="replaceDialogAddForm"
                     :option="replaceDialogAddFormOption">
          </avue-form>
        </el-main>
        <el-aside width="50%">
          <el-card shadow="never" style="height:460px;overflow-y: auto">
            <el-timeline>
              <el-timeline-item
                  v-for="(activity, index) in replaceActivities"
                  :key="index"
                  :timestamp="activity.timeString"
                  color="#39b1e4"
                  icon="el-icon-mor"
                  placement="top"
                  size="large"
              >
                <el-card>
                  <p>类型： {{ activity.orderChangeName }}</p>
                  <p>内容： {{ activity.name }}</p>
                  <p>意见: {{ activity.des }}</p>
                  <h5 v-if="activity.fileId != null && activity.fileId != ''">
                    <el-button type="text" @click="downloadById(activity.fileId,activity.fileName)">
                      {{ activity.fileName }}
                    </el-button>
                  </h5>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-aside>

      </el-container>
    </basic-dialog>
    <basic-dialog v-model="replaceDialog.childrenVisible" :showSubmitBtn="false" title="选择替换计划" width="1200"
                  @cancel="handlerReplaceAddChildrenCancel"
                  @submit="handlerReplaceAddChildrensSubmit">
      <basic-crud :apiListParams="ReplaceAddChildrenParams"
                  :option="replaceCrudOption"
                  apiGetListUrl="/mes/mesWorkOrderController/listSameModelName">
        <template #showLevel="{row}">
          <el-tooltip v-if="row.showLevel == 1" class="item" content="已经超期了" effect="dark" placement="top-start">
            <el-icon :size="20" color="red">
              <BellFilled/>
            </el-icon>
          </el-tooltip>
          <el-tooltip v-else-if="row.showLevel == 2" class="item" content="剩余交付时间5天内" effect="dark"
                      placement="top-start">
            <el-icon :size="20" color="orange">
              <BellFilled/>
            </el-icon>
          </el-tooltip>
          <el-tooltip v-else-if="row.showLevel == 3" class="item" content="剩余交付时间5到10天内" effect="dark"
                      placement="top-start">
            <el-icon :size="20" color="yellow">
              <BellFilled/>
            </el-icon>
          </el-tooltip>
          <el-tooltip v-else-if="row.showLevel == 4" class="item" content="交付日期可控" effect="dark" placement="top-start">
            <el-icon :size="20" color="green">
              <BellFilled/>
            </el-icon>
          </el-tooltip>
          <el-tooltip v-else-if="row.showLevel == 5" class="item" content="还未派工" effect="dark" placement="top-start">
            <el-icon :size="20" color="gray">
              <BellFilled/>
            </el-icon>
          </el-tooltip>
          <el-tooltip v-else-if="row.showLevel == 6" class="item" content="已经入库" effect="dark" placement="top-start">
            <el-icon :size="20" color="lightgreen">
              <BellFilled/>
            </el-icon>
          </el-tooltip>
        </template>
        <template #menu="{ row }">
          <el-button
              class="ml10"
              icon="el-icon-circle-check"
              type="text"
              @click="handelReplace(row)"
          >替换
          </el-button>
        </template>
      </basic-crud>
    </basic-dialog>
    <!-- 行调整 -->
    <basic-dialog v-model="lineAdjustDialog.visible" title="计划调整" width="1000"
                  @cancel="handlerLineAdjustAddCancel"
                  @submit="handlerLineAdjustSubmit">
      <el-container>
        <el-main style="margin-right: 20px">
          <!-- 复用计划调整option配置 -->
          <avue-form ref="lineAdjustRefs" v-model="lineAdjustDialogAddForm"
                     :option="djustDialogAddFormOption">
          </avue-form>
        </el-main>
        <el-aside width="50%">
          <el-card shadow="never" style="height:460px;overflow-y: auto">
            <el-timeline>
              <el-timeline-item
                  v-for="(activity, index) in lineAdjustActivities"
                  :key="index"
                  :timestamp="activity.timeString"
                  color="#39b1e4"
                  icon="el-icon-mor"
                  placement="top"
                  size="large"
              >
                <el-card>
                  <p>类型： {{ activity.orderChangeName }}</p>
                  <p>内容： {{ activity.name }}</p>
                  <p>意见: {{ activity.des }}</p>
                  <h5 v-if="activity.fileId != null && activity.fileId != ''">
                    <el-button type="text" @click="downloadById(activity.fileId,activity.fileName)">
                      {{ activity.fileName }}
                    </el-button>
                  </h5>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-aside>

      </el-container>
    </basic-dialog>
    <!-- 规程 -->
    <basic-dialog v-model="regulationDialog.visible" :showSubmitBtn="false" title="查看或替换规程" width="1000">
      <basic-crud ref="regulationCrudRef" :apiListParams="regulationParams" :defaultListParams="{}"
                  :option="regulationOption"
                  businessUrl="/mes/workOrderTargetController">
        <template #menu-left>
          <el-button
              icon="el-icon-plus"
              type="primary"
              @click="onOpenWorksplus"
          >新增
          </el-button>
        </template>
        <template #obsoleteFlag="{ row }">
          <el-tag v-if="row.obsoleteFlag === 'true'" type="danger"> 是</el-tag>
          <el-tag v-else>否</el-tag>
        </template>
        <template #menu="{ row }">
          <el-button
              :disabled="row.obsoleteFlag === 'true' ? true : false"
              class="ml10"
              icon="el-icon-circle-check"
              type="text"
              @click="handelEditByrules(row)"
          >替换
          </el-button
          >
          <el-button
              :disabled="row.obsoleteFlag === 'true' ? true : false"
              class="ml10"
              icon="el-icon-delete"
              type="text"
              @click="handleEditByCancel(row)"
          >作废
          </el-button
          >
        </template>
      </basic-crud>

    </basic-dialog>
    <!-- 行规程替换 -->
    <select-technology ref="SelectTechnologyEditRef" apiGetUrl="/mpm/processSpecificationController/listReplace"
                       @refresh="handleRegulationRefresh"></select-technology>
    <!-- 行规程新增 -->
    <select-technology ref="SelectTechnologyAddRef" @refresh="handleRegulationRefresh"></select-technology>
  </el-container>
</template>

<script setup>
import {
  getModelName,
  getProductList,
  setAssigner,
  getProductionsAdd,
  forcedFinish,
  putWorkOrder,
  delDeleteById,
  getProductionAdd,
  postTransferPlan,
  editPlanName,
  listChangeHis,
  replaceCode,
  postCancle,
  adjustListFiles
} from "../../../apis/generate/productionPlan";
import {downloadFile} from "../../../utils/file";
import SelectRequestAdd from './selectRequestAdd.vue';
import SelectTechnology from "./selectTechnology.vue";
import ImprotFile from '../../../components/FileUp/ImprotFile.vue'
import {useUserStore} from '@/store/user';
import axios from "axios";
import {formatDate} from "../../../utils/formatTime";
import {ElMessage} from "element-plus";

const {token} = useUserStore();
const confirm = ({msg, title = '提示', confirmButtonText = '确定', cancelButtonText = '取消', type = 'warning'}) => {
  return ElMessageBox.confirm(msg, title, {
    confirmButtonText,
    cancelButtonText,
    type
  })
}

const option = ref({
  addBtn: false,
  cellBtn: false,
  editBtn: false,
  delBtn: false,
  viewBtn: false,
  menuWidth: 380,
  column: [
    {
      label: '预警',
      prop: 'showLevel',
      fixed: true,
      align: 'center',
      width: 50
    },
    {
      label: "状态",
      prop: "status",
      width: 95,
      align: 'center',
      slot: true,
      search: true,
      searchType: "select",
      fixed: true,
      display: false,
      multiple: true,
      searchSpan: 4,
      overHidden: false,
      statusShow: true,
      statusTag: true,
      statusTypeMap: {
        Suspended: 'danger',
        Obsoleted: 'info',
        ExecuteFinish: 'success',
        Finish: 'success',
        Auditing:'warning'
      },
    },
    {
      label: "完工率",
      prop: 'percent',
      width: 70
    },
    {
      label: '计划编号',
      prop: 'sourceCode',
      minWidth: 200,
      fixed: true,
      search: true,
      searchSpan: 4,
      overHidden: true,
    },
    {
      label: "erp计划名称",
      prop: "planAuditOrderName",
      display: false,
      overHidden: true,
      fixed: true,
      width: 120,
    },
    {
      label: "项目号",
      prop: "code",
      fixed: true,
      sortable: true,
      display: false,
      width: 130,
      overHidden: true,
      searchSpan: 4,
      search: true,
    },
    {
      label: '数量',
      prop: 'quantity',
      width: 60,
      display: false
    },
    {
      label: "产品名称",
      prop: "pdmProductName",
      sortable: true,
      searchSpan: 4,
      display: false,
      overHidden: true,
      minWidth: 200,
    },
    {
      label: "产品型号",
      prop: "modelName",
      sortable: true,
      overHidden: true,
      width: 120,
      searchSpan: 4,
      display: false,
      search: true,
      formatter: (val) => {
        return val.modelName;
      }
    },
    {
      label: "产品编号",
      prop: "pdmProductCode",
      sortable: true,
      overHidden: true,
      cell: true,
      display: false,
      minWidth: 150,
      searchSpan: 4,
      search: true,
    },
    {
      label: '产品主管',
      prop: 'assignerName',
      width: 100,
      search: true,
      searchSpan: 4,
      display: false
    },
    {
      label: "规程编号",
      prop: "primaryTargetCode",
      width: 120,
      overHidden: true,
      search: true,
      sortable: true,
      searchSpan: 4,
      display: false,
      slot: true,
    },
    {
      label: "计划开始日期",
      prop: "needStartDate",
      sortable: true,
      width: 120,
      display: false,
      formatter: (row) => {
        return row.needStartDate?.substring(0, 10);
      },
    },
    {
      label: "计划结束日期",
      prop: "needEndDate",
      sortable: true,
      width: 120,
      display: false,
      search: true,
      searchSpan: 8,
      searchType: 'daterange',
      formatter: (row) => {
        return row.needEndDate?.substring(0, 10);
      },
    },
    {
      label: "计划交付日期",
      prop: "deliveryDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.deliveryDate?.substring(0, 10);
      },
    },
    {
      label: "开工日期",
      prop: "beginDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.beginDate?.substring(0, 10);
      },
    },
    {
      label: "完工日期",
      prop: "finishDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.finishDate?.substring(0, 10);
      },
    },
    {
      label: "入库日期",
      prop: "realDeliveryDate",
      sortable: true,
      display: false,
      width: 120,
      formatter: (row) => {
        return row.realDeliveryDate?.substring(0, 10);
      },
    },
    {
      label: "紧急程度",
      prop: "exigencyLevel",
      display: false,
      width: 80,
      type: "select",
      dicData: [
        {
          label: "不紧急",
          value: "none",
        },
        {
          label: "一般",
          value: "normal",
        },
        {
          label: "紧急",
          value: "exigency",
        },
        {
          label: "非常紧急",
          value: "veryExigency",
        },
      ],
      formatter: (val) => {
        return val.exigencyLevelText;
      },
    },
    {
      label: "军检",
      prop: "armyCheck",
      display: false,
      width: 60,
      type: "switch",
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }],
    },
    {
      label: "批次号",
      prop: "batchNum",
      display: false,
      overHidden: true,
      width: 120,
    },
    {
      label: '配套机型',
      prop: 'targetModel',
      display: false,
      overHidden: true,
      width: 120
    },
    {
      label: "手动计划依据",
      prop: "sourceBasis",
      display: false,
      slot: true,
      width: 120,
    }
  ]
});
const loadingBtn = ref({
  eprAddPlanLoading: false,
  manualAddPlanLoading: false,
  setSpecificationLoading: false,
  deleteRowLoading: false,
  setAssignerLoading: false,
  specificationLoading: false,
  adjustmentLoading: false,
  adjustmentAllLoading: false,
  exportMonthLoading: false,
  warehousingLoading: false,
  onOpenWorksReplaceLoading: false,
  editPlanNameLoading: false,
  productsAddLoading: false,
  forcedFinishPlanLoading: false,
  importFinishPlanLoading: false
});
const formatPercent = (percent) => {
  if (!percent) {
    return '0.0%';
  }
  return `${percent}%`;
}

//刷新列表
const handleRefresh = () => {
  crudRef.value.getList();
};
const SelectRequestAddRef = ref(null);

// erp新增计划
const erpAddClickHandler = () => {
  SelectRequestAddRef.value.openDialog();
};
// 手动新增计划表单
const formProductRefs = ref(null)
// 手动新增计划弹窗
const SelectRequestAddDialog = ref({
  loading: false,
  submitLoading: false,
  visible: false
});
const SelectRequestAddForm = ref({files: []});
const SelectRequestAddFormOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 120,
  column: [
    {
      label: "计划编号",
      prop: "sourceCode",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "请输入计划编号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "项目号",
      prop: "code",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "请输入项目号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "数量",
      prop: "quantity",
      type: "number",
      labelWidth: "140",
      gutter: 32,
      span: 12,
      rules: [
        {
          required: true,
          message: "请输入数量",
          trigger: "blur",
          type: "number",
        },
      ],
    },
    {
      label: "型号",
      prop: "pdmModelName",
      type: "select",
      labelWidth: "140",
      formslot: true,
      rules: [
        {
          required: true,
          message: "型号不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "产品名称",
      prop: "pdmProductName",
      labelWidth: "140",
      formslot: true,
      rules: [
        {
          required: true,
          message: "产品名称不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "军检",
      prop: "armyCheck",
      labelWidth: "140",
      width: 90,
      type: "switch",
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }],
      value: 'false'
    },
    {
      label: "计划日期",
      prop: "needDate",
      type: "datetimerange",
      labelWidth: "140",
      format: "YYYY-MM-DD",
      span: 24,
      rules: [
        {
          required: true,
          message: "请选择计划日期",
          trigger: "blur",
        },
      ],
      startPlaceholder: "计划开始日期",
      endPlaceholder: "计划结束日期",
    },
    {
      label: "计划交付日期",
      prop: "deliveryDate",
      labelWidth: "140",
      type: "date",
      rules: [
        {
          required: true,
          message: "请选择计划交付日期",
          trigger: "blur",
        },
      ],
    },
    {
      label: "配套机型",
      prop: "targetModel",
      labelWidth: "140",
      component: 'BasicCrudTableSelect',
      width: 150,
      comProps: {
        saveFieldMap: {targetModel: 'name'},
        comType: 'form',
      },
      crudProps: {
        apiReferUrl: '/mes/mesApplyProductController/referGrid',
        option: {
          menu: false,
          column: [
            {prop: 'name', label: '机型名称'},
            {prop: 'orderNum', label: '排序号'}
          ]
        }
      },
      curForm: SelectRequestAddForm,
      change: (newV) => {
        SelectRequestAddForm.value = newV;
        formProductRefs.value?.clearValidate();
      },
      rules: [
        {
          required: true,
          message: "请选择配套机型",
          trigger: "blur",
        },
      ],
    },
    {
      label: "审批单编号",
      prop: "planAuditOrderCode",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
    },
    {
      label: "审批单名称",
      prop: "planAuditOrderName",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
    },
    {
      label: '批次号',
      prop: 'batchNum',
      span: 12,
      labelWidth: "140",
      rules: [{
        required: true,
        message: "批次号不能为空",
        trigger: "blur"
      }],
    },
    {
      label: "上传依据",
      prop: "files",
      gutter: 32,
      span: 12,
      type: 'upload',
      labelWidth: "140",
      formslot: true,
    },
  ]
});
const dicModuName = ref([]);
const uploadObject = ref({
  propsHttp: {
    res: "obj",
    name: "obj.name",
    url: "fileViewUrl",
  },
  headers: {
    'h-authorization-token': token
  },
  action: '/API/mes/fileController/uploadFile',
});
const dicProductName = ref([]);
const crudRef = ref(null)
const selectList = ref([]);
const workOrderId = ref(null);
// 表格多选
const handleChangeSelect = (row) => {
  selectList.value = row;
  workOrderId.value = row.map((item) => item.id).toString();
}
// 手动新增计划
const erpHandClickHandler = () => {
  SelectRequestAddDialog.value.visible = true;
  getModelName({orderMethod: 'asc', orderBy: 'code'}).then((data) => {
    console.log(data);
    dicModuName.value = data;
  }).catch(() => ElMessage.$message.error("查询产品信息失败"));
};
//手动新增计划保存
const handleSelectRequestAddSubmit = () => {
  if (!SelectRequestAddForm.value.pdmProductName || SelectRequestAddForm.value.pdmProductName == null) {
    ElMessage.error("没有选择产品，不能保存");
    return false;
  }
  let productName = SelectRequestAddForm.value.pdmProductName;
  SelectRequestAddForm.value.needStartDate = formatDate(SelectRequestAddForm.value.needDate[0], "yyyy-MM-dd");
  SelectRequestAddForm.value.needEndDate = formatDate(SelectRequestAddForm.value.needDate[1], "yyyy-MM-dd");
  SelectRequestAddForm.value.deliveryDate = formatDate(SelectRequestAddForm.value.deliveryDate, "yyyy-MM-dd");
  SelectRequestAddForm.value.pdmProductName = productName.split("#")[1];
  formProductRefs.value.validate((validate, done) => {
    if (validate) {
      SelectRequestAddForm.value.onlyProduct = true;
      getProductionAdd(SelectRequestAddForm.value)
          .then((res) => {
            ElMessage.success("新增计划成功！");
            handleSelectRequestAddCancel();
            handleRefresh();
          })
          .catch((err) => {
            console.log(err);
          }).finally(() => {
        done();
      });
    }
  });
}
// 手动新增计划保存取消
const handleSelectRequestAddCancel = () => {
  SelectRequestAddDialog.value.visible = false;
  formProductRefs.value?.resetFields();
  SelectRequestAddForm.value.files = [];
};
const gteProduct = (val) => {
  SelectRequestAddForm.value.pdmProductName = "";
  getProductList({code: val}).then((data) => {
    dicProductName.value = data;
  });
};
// 规程子组件
const SelectTechnologyRef = ref(null);
// 设置规程
const addByWorkHandler = () => {
  if (!selectList.value || selectList.value.length == 0) {
    ElMessage.error("没有选择计划条目，无法设置规程");
    return false;
  }

  var productId = "";
  var hasIndex = 0;
  var notEqual = false;
  for (let i = 0; i < selectList.value.length; i++) {
    var record = selectList.value[i];
    if (productId == "") {
      productId = record.pdmProduct;
    } else {
      if (productId != record.pdmProduct) {
        ElMessage.error(
            "只有计划关联的产品相同的时候才能批量设置规程，请先查证"
        );
        notEqual = true;
        break;
      }
    }
    if (record.primaryTargetId != null && record.primaryTargetId != "") {
      hasIndex++;
    }
  }
  if (notEqual) {
    return;
  }
  if (hasIndex > 0) {
    const confirmText = `有` + hasIndex + `条计划已经添加了规程，如果要替换请点击右侧的【查看或替换规程】；如果确实需要继续添加规程，请点击【确定】`;
    confirm({msg: confirmText}).then(() => {
      let params = {
        productCode: selectList.value[0].modelName,
        primaryTargetId: selectList.value[0].primaryTargetId || "",
        workOrderId: workOrderId.value,
        type: 'plan'
      };
      SelectTechnologyRef.value.openDialog(params);
    });
  } else {
    let params = {
      productCode: selectList.value[0].modelName,
      primaryTargetId: selectList.value[0].primaryTargetId || "",
      workOrderId: workOrderId.value,
    };
    SelectTechnologyRef.value.openDialog(params);
  }
};
// 产品主管对话框
const userVisible = ref(null);
const userProductRef = ref(null);
// 设置产品主管
const setAssignerHandler = () => {
  if (!selectList.value || selectList.value.length == 0) {
    ElMessage.error("没有选择计划条目，无法设置负责人");
    return false;
  }
  //校验是否可以设置，当加工完成和入库等状态的时候，不能再执行
  let cannotEdit = selectList.value.find((item) => (item.status == 'ExecuteFinish' || item.status == 'Finish'));
  if (cannotEdit) {
    ElMessage.error("计划的状态是加工完成和已入库的时候，不能再修改");
    return false;
  }
  userVisible.value = true;
};
// 设置产品主管保存
const handleUserSubmit = (data) => {
  const submitData = {
    id: selectList.value.map((val) => val.id).join(","),
    assigner: data[0].id
  };
  setAssigner(submitData).then((res) => {
    ElMessage.success("设置产品主管成功");
    userVisible.value = false;
    handleRefresh();
    userProductRef.value.handlerCancel();
    userVisible.value = false;
  });
};
// 导出计划
const exportMonth = () => {
  confirm({msg: '是否导出本月的计划'}).then(() => {
    axios({
      method: "get",
      url: "/API/mes/mesWorkOrderController/exportMonth",
      responseType: "blob",
      headers: {
        "Content-Type": "application/json;application/octet-stream",
        "h-authorization-token": token,
      },
    }).then((res) => {
      let fileName = window.decodeURI(
          res.headers["content-disposition"].split(";")[1].split("=")[1],
          "UTF-8"
      ); //获取压缩包文件名称
      let blob = new Blob([res.data], {type: "application/zip"});
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement("a"); // 创建a标签
      link.href = url;
      link.download = fileName; // 重命名文件
      link.click();
      URL.revokeObjectURL(url); // 释放内存
    });
  });
};
// 计划补录对话框参数
const productionPlanPushsDialog = ref({
  visible: false,
  loading: false,
  submitLoading: false
});
// 计划补录绑定表单
const productionPlanPushsAddForm = ref({});
// 计划补录表单配置
const productionPlanPushsAddFormOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 120,
  column: [
    {
      label: "计划编号",
      prop: "sourceCode",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "请输入计划编号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "项目号",
      prop: "code",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "请输入项目号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "数量",
      prop: "quantity",
      type: "number",
      labelWidth: "140",
      gutter: 32,
      span: 12,
      rules: [
        {
          required: true,
          message: "请输入数量",
          trigger: "blur",
          type: "number",
        },
      ],
    },
    {
      label: "型号",
      prop: "pdmModelName",
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "型号不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "产品名称",
      prop: "pdmProductName",
      labelWidth: "140",
      rules: [
        {
          required: true,
          message: "产品名称不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "计划日期",
      prop: "needDate",
      type: "datetimerange",
      labelWidth: "140",
      format: "YYYY-MM-DD",
      span: 24,
      rules: [
        {
          required: true,
          message: "请选择计划日期",
          trigger: "blur",
        },
      ],
      startPlaceholder: "计划开始日期",
      endPlaceholder: "计划结束日期",
    },
    {
      label: "计划交付日期",
      prop: "deliveryDate",
      labelWidth: "140",
      type: "date",
      rules: [
        {
          required: true,
          message: "请选择计划交付日期",
          trigger: "blur",
        },
      ],
    },
    {
      label: "入库日期",
      prop: "realDeliveryDate",
      labelWidth: "140",
      type: "date",
      rules: [
        {
          required: true,
          message: "请选择入库日期",
          trigger: "blur",
        },
      ],
    },
    {
      label: "配套机型",
      prop: "targetModel",
      labelWidth: "140",
      component: 'BasicCrudTableSelect',
      width: 150,
      comProps: {
        saveFieldMap: {targetModel: 'name'},
        comType: 'form',
      },
      crudProps: {
        apiReferUrl: '/mes/mesApplyProductController/referGrid',
        option: {
          menu: false,
          column: [
            {prop: 'name', label: '机型名称'},
            {prop: 'orderNum', label: '排序号'}
          ]
        }
      },
      curForm: productionPlanPushsAddForm,
      change: (newV) => {
        productionPlanPushsAddForm.value = newV;
        formProductPlanRefs.value?.clearValidate();
      },
      rules: [
        {
          required: true,
          message: "请选择配套机型",
          trigger: "blur",
        },
      ],
    },
    {
      label: "审批单编号",
      prop: "planAuditOrderCode",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
    },
    {
      label: "审批单名称",
      prop: "planAuditOrderName",
      type: "input",
      gutter: 32,
      span: 12,
      labelWidth: "140",
    }, {
      label: '批次号',
      prop: 'batchNum',
      span: 12,
      labelWidth: "140",
      rules: [{
        required: true,
        message: "批次号不能为空",
        trigger: "blur"
      }],
    }
  ]
});
// 计划补录按钮事件
const productionPlanPushsHandler = () => {
  productionPlanPushsDialog.value.visible = true;
};
const formProductPlanRefs = ref(null);
// 计划补录保存
const handleProductionPlanPushsAddSubmit = () => {
  const form = productionPlanPushsAddForm.value;
  if (Array.isArray(form.needDate) && form.needDate.length >= 2) {
    // 使用解构赋值简化数组访问
    const [startDate, endDate] = form.needDate;
    const format = date => formatDate(date, "yyyy-MM-dd");
    form.needStartDate = format(startDate);
    form.needEndDate = format(endDate);
  }
  // 格式化其他日期字段
  form.deliveryDate = formatDate(form.deliveryDate, "yyyy-MM-dd");
  form.realDeliveryDate = formatDate(form.realDeliveryDate, "yyyy-MM-dd");
  formProductPlanRefs.value.validate((validate, done) => {
    console.log(validate)
    console.log(done)
    if (!validate) {
      // 验证失败时调用 done
      done();
      return;
    }
    if (validate) {
      form.onlyProduct = true;
      getProductionsAdd(form)
          .then(() => {
            ElMessage.success("计划补录成功！");
            handleProductionPlanPushsAddCancel();
            handleRefresh();
          })
          .catch((err) => (() => {
            ElMessage.error(err);
          })).finally(() => {
        done();
      });
    }
  })
};
// 计划补录取消
const handleProductionPlanPushsAddCancel = () => {
  productionPlanPushsDialog.value.visible = false;
  formProductPlanRefs.value?.resetFields();
};
// 完成计划参数
const forcedFinishPlanDialog = ref({
  visible: false
});
const forcedFinishPlanForm = ref({});
const forcedFinishPlanRef = ref(null);
const forcedFinishPlanFormOption = ref({
  labelWidth: 140,
  submitBtn: false,
  emptyBtn: false,
  column: [{
    label: '说明',
    prop: 'des',
    rows: 20,
    minRows: 10,
    type: 'textarea',
    span: 24
  }, {
    label: '附件',
    prop: 'fileUpload',
    type: 'upload',
    action: "/API/mes/fileController/uploadFile",
    propsHttp: {
      res: "obj",
      name: "obj.name",
      url: "name",
    },
    span: 24,
    headers: {
      'h-authorization-token': token
    },
  }]
});
const forcedPlan = ref(null);
// 完成计划
const forcedFinishPlanHandler = () => {
  if (!selectList.value || selectList.value.length === 0) {
    ElMessage.error("请先选择数据后再操作");
    return false;
  }
  confirm({msg: '是否要强制完成计划?,需要确认'}).then(() => {
    if (!selectList.value || selectList.value.length === 0) {
      ElMessage.error("请先选择数据后再操作");
      return false;
    }
    forcedPlan.value = selectList.value;
    forcedFinishPlanDialog.value.visible = true;
  });
};
// 完成计划取消
const forcedFinishPlanDialogCancel = () => {
  forcedFinishPlanDialog.value.visible = false;
  forcedFinishPlanRef.value?.resetFields();
  forcedFinishPlanForm.value = {};

};
// 完成计划保存
const forcedFinishPlanDialogSubmit = () => {
  if ((!forcedFinishPlanForm.value.fileId || '' === forcedFinishPlanForm.value.fileId) && (!forcedFinishPlanForm.value.des || '' === forcedFinishPlanForm.value.des)) {
    ElMessage.error("说明或者附件必须至少添加一项");
    return false;
  }
  forcedFinishPlanForm.value.workOrderId = forcedPlan.value.map(val => val.id).join(',');
  forcedFinish(forcedFinishPlanForm.value).then(res => {
    ElMessage.success("执行成功");
    forcedFinishPlanDialogCancel();
  });
};
// 完成计划上传文件后
const uploadAfter = (obj, done) => {
  if (obj) {
    forcedFinishPlanForm.value.fileId = obj.id;
    forcedFinishPlanForm.value.fileName = obj.name + ((obj.fileExtension && obj.fileExtension != '') ? ("." + obj.fileExtension) : "");
  }
  done();
};
// 导入补录计划参数
const fileVisible = ref(false);
const importFinishPlanHandler = () => {
  fileVisible.value = true;
};
// 多选调整参数
const adjustDialog = ref({
  visible: false
});
const adjustDialogAddForm = ref({});
const djustDialogAddRefs = ref(null);
const adjustFileObj = computed(() => {
  return {
    fileObjectDTOS: JSON.stringify(selectionItemAdjust.value)
  }
});
const djustDialogAddFormOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 120,
  column: [
    {
      label: "计划开始日期",
      prop: "newPlanStart",
      type: "datetime",
      format: 'YYYY年MM月DD日',
      valueFormat: 'YYYY-MM-DD',
      span: 24,
      rules: [
        {
          required: true,
          message: "请选择计划开始日期",
          trigger: "blur",
        },
      ]
    },
    {
      label: "计划结束日期",
      prop: "newPlanEnd",
      format: 'YYYY年MM月DD日',
      valueFormat: 'YYYY-MM-DD',
      type: "datetime",
      span: 24,
      rules: [
        {
          required: true,
          message: "请选择计划结束日期",
          trigger: "blur",
        },
      ]
    },
    {
      label: '调整依据内容',
      prop: 'des',
      type: 'textarea',
      placeholder: "请输入调整依据的内容，或者是在下方上传附件",
      rows: 8,
      span: 24
    },
    {
      label: '附件',
      prop: 'fileUpload',
      type: 'upload',
      action: "/API/mes/fileController/uploadFileForOwns",
      propsHttp: {
        res: "data[0]",
        name: "name",
        url: "fileViewUrl",
      },
      data: adjustFileObj,
      span: 24,
      headers: {
        'h-authorization-token': token
      },
    }
  ]
});
// 多选调整按钮事件
const adjustClickHandler = () => {
  const selectedCount = selectList.value.length;

  if (selectedCount === 0) {
    ElMessage.error('请至少选择一条数据');
    return;
  }

  const selectedIds = selectList.value.map(item => item.id).join(',');
  const firstItem = selectList.value[0];

  adjustDialogAddForm.value = {
    ...adjustDialogAddForm.value,
    workOrderId: selectedIds,
    newPlanEnd: firstItem.needEndDate,
    newPlanStart: firstItem.needStartDate
  };

  if (selectedCount === 1) {
    adjustDialog.value.visible = true;
    getFileAdjustHandler()
    return;
  }

  // 多条数据需要检查sourceCode是否相同
  const firstSourceCode = firstItem.sourceCode;
  const allSameSourceCode = selectList.value.every(item => item.sourceCode === firstSourceCode);

  if (allSameSourceCode) {
    adjustDialog.value.visible = true;
    getFileAdjustHandler();
  } else {
    ElMessage.error('请检查已勾选数据的计划编号是否相等!');
  }
};
const selectionItemAdjust = ref({});
// 多选调整获取文件
const getFileAdjustHandler = () => {
  const params = {
    ownId: selectList.value.map(item => item.id).join(',') || "",
    ownBus: selectList.value[0].bus
  };
  adjustListFiles(params).then((data) => {
    if (data.length > 0) {
      selectionItemAdjust.value = selectList.value.map(item => {
        const selectionItem = {
          ownId: item.id,
          ownBus: item.bus,
          updateFileFlag: false,
          id: ""
        };
        const matchedItem = data.find(dataItem => dataItem.ownId === item.id);

        if (matchedItem) {
          selectionItem.id = matchedItem.id;
          selectionItem.updateFileFlag = true;
        }

        return selectionItem;
      });
      console.log(selectionItemAdjust.value);
    } else {
      selectionItemAdjust.value = selectList.value.map(item => {
        return {
          ownId: item.id,
          ownBus: item.bus,
          updateFileFlag: false,
          id: ""
        };
      });
    }
  });
};
// 多选调整取消
const handlerAdjustAddCancel = () => {
  adjustDialog.value.visible = false;
  djustDialogAddRefs.value?.resetFields();
  adjustDialogAddForm.value = {};
};
// 多选调整保存
const handlerAdjustAddSubmit = () => {
  adjustDialogAddForm.value.newPlanStart = formatDate(
      adjustDialogAddForm.value.newPlanStart,
      "yyyy-MM-dd"
  );
  adjustDialogAddForm.value.newPlanEnd = formatDate(
      adjustDialogAddForm.value.newPlanEnd,
      "yyyy-MM-dd"
  );

  putWorkOrder(adjustDialogAddForm.value)
      .then((res) => {
        ElMessage.success("修改计划成功!");
        handlerAdjustAddCancel();
        handleRefresh();
      });
};
// 删除
const delCrudClickHandler = (row) => {
  confirm({msg: '是否要强制完成计划?,需要确认', confirmButtonText: '删除'}).then(() => {
    delDeleteById(row.id)
        .then((res) => {
          ElMessage.success("删除成功");
          handleRefresh()
        })
  })
};
// 入库参数
const beStoreDialog = ref({
  visible: false
});
const beStoreAddRefs = ref(null);
const beStoreForm = ref({});
const beStoreRow = ref({});
const beStoreFormOption = ref({
  labelWidth: 140,
  submitBtn: false,
  emptyBtn: false,
  column: [
    {
      label: "入库日期",
      prop: "realDeliveryDate",
      type: "date",
      span: 24,
      labelWidth: 100,
      rules: [
        {
          required: true,
          message: "请选择入库日期",
          trigger: "blur",
        },
      ],
    },
  ]
});
// 入库按钮事件
const openStoreHandler = (row) => {
  beStoreDialog.value.visible = true;
  beStoreRow.value.id = row.id;
};
// 入库取消
const beStoreAddCancel = () => {
  beStoreDialog.value.visible = false;
  beStoreAddRefs.value.resetFields();
};
// 入库确定
const beStoreAddSubmit = () => {
  beStoreAddRefs.value.validate((validate, done) => {
    if (validate) {
      const params = {...beStoreForm.value, id: beStoreRow.value.id}
      console.log(params)
      postTransferPlan([params])
          .then(() => {
            ElMessage.success("入库成功！");
            beStoreAddCancel();
            handleRefresh();
          })
          .catch(() => {
          }).finally(() => {
        done();
      })
    }
  })
};
// 调整名称按钮事件
const editPlanNameHandler = (row) => {
  ElMessageBox.prompt('请输入要修改的名称', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputErrorMessage: '取消操作',
  }).then(({value}) => {
    const params = {...row, planAuditOrderName: value};
    editPlanName(params).then(() => {
      ElMessage.success('修改成功');
    }).catch(err => {
      ElMessage.error(err + '修改失败');
    })
  })
};
// 替换参数
const replaceDialog = ref({
  visible: false,
  childrenVisible: false
})
const ReplaceAddChildrenParams = computed(() => {
  return {
    id: replaceRow.value.id
  }
})
const replaceRow = ref({});
const replaceDialogAddForm = ref({});
const replaceActivities = ref([]);
const replaceDialogAddRefs = ref(null);
const replaceDialogAddFormOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  labelWidth: 120,
  column: [
    {
      label: "替换计划",
      prop: "newCode",
      span: 24,
      rules: [
        {
          required: true,
          message: "请选择替换计划",
          trigger: "submit",
        },
      ],
      click: () => {
        replaceDialog.value.childrenVisible = true;
      }
    },
    {
      label: "替换意见",
      prop: "replaceDes",
      type: "textarea",
      placeholder: '请输入替换意见，或者是在下方上传附件',
      span: 24,
      rules: [
        {
          required: true,
          message: "请输入替换意见，或者是在下方上传附件",
          trigger: "blur",
        },
      ]
    },
    {
      label: '替换依据',
      prop: 'fileUpload',
      type: 'upload',
      action: "/API/mes/fileController/uploadFile",
      propsHttp: {
        res: "obj",
        name: "obj.name",
        url: "fileViewUrl",
      },
      span: 24,
      headers: {
        'h-authorization-token': token
      },
    }
  ]
});
const replaceCrudOption = ref({
  highlightCurrentRow: true,
  addBtn: false,
  cellBtn: false,
  editBtn: false,
  delBtn: false,
  viewBtn: false,
  menuWidth: 120,
  height: 600,
  column: [
    {
      label: '预警',
      prop: 'showLevel',
      fixed: true,
      align: 'center',
      width: 80
    },
    {
      label: "状态",
      prop: "status",
      width: 90,
      slot: true,
      searchType: "select",
      fixed: true,
      display: false,
      statusShow: true,
      statusTag: true,
      align: 'center',
      statusTypeMap: {
        Suspended: 'danger',
        ExecuteFinish: 'success',
        Obsoleted: 'info',
      },
    },
    {
      label: "项目号",
      prop: "code",
      fixed: true,
      display: false,
      width: 130,
      search: true,
      overHidden: true,
    }, {
      label: '数量',
      prop: 'quantity',
      width: 70,
      display: false
    },
    {
      label: "产品编号",
      prop: "pdmProductCode",
      cell: true,
      display: false,
      search: true,
      width: 150,
    }, {
      label: '产品主管',
      prop: 'assignerName',
      width: 90,
      display: false
    },
    {
      label: "规程编号",
      prop: "primaryTargetCode",
      width: 200,
      display: false,
      search: true,
      slot: true,
    },
    {
      label: "计划开始日期",
      prop: "needStartDate",
      width: 120,
      display: false,
      formatter: (row) => {
        return formatDate(row.needStartDate, "yyyy-MM-dd");
      },
    },
    {
      label: "计划结束日期",
      prop: "needEndDate",
      width: 120,
      display: false,
      formatter: (row) => {
        return formatDate(row.needEndDate, "yyyy-MM-dd");
      },
    },
    {
      label: "计划交付日期",
      prop: "deliveryDate",
      display: false,
      width: 120,
      formatter: (row) => {
        return formatDate(row.deliveryDate, "yyyy-MM-dd");
      },
    },
    {
      label: "完工日期",
      prop: "finishDate",
      display: false,
      width: 120,
      formatter: (row) => {
        return formatDate(row.finishDate, "yyyy-MM-dd");
      },
    },
    {
      label: "紧急程度",
      prop: "exigencyLevel",
      display: false,
      width: 80,
      type: "select",
      dicData: [
        {
          label: "不紧急",
          value: "none",
        },
        {
          label: "一般",
          value: "normal",
        },
        {
          label: "紧急",
          value: "exigency",
        },
        {
          label: "非常紧急",
          value: "veryExigency",
        },
      ],
      formatter: (val) => {
        return val.exigencyLevelText;
      },
    },
    {
      label: "军检",
      prop: "armyCheck",
      display: false,
      width: 60,
      type: "switch",
      dicData: [{
        label: '否',
        value: 'false'
      }, {
        label: '是',
        value: 'true'
      }],
    }, {
      label: "批次号",
      prop: "batchNum",
      display: false,
      width: 90,
    },
  ]
})
// 替换按钮事件
const replaceClickHandler = (row) => {
  replaceDialog.value.visible = true;
  getChangeReplaceHis(row.id);
  replaceRow.value = row;
};
// 替换取消
const handlerReplaceAddCancel = () => {
  replaceDialog.value.visible = false;
  replaceDialogAddRefs.value.resetFields();
};
// 替换保存
const handlerReplaceAddSubmit = () => {
  replaceDialogAddRefs.value.validate((validate, done) => {
    if (validate) {
      replaceDialogAddForm.value['id'] = replaceRow.value.id;
      replaceCode(replaceDialogAddForm.value).then(() => {
        ElMessage.success('替换成功');
        handlerReplaceAddCancel();
        handleRefresh();
      }).finally(() => {
        done();
      })
    }
  })
};
// 获取替换信息
const getChangeReplaceHis = (id) => {
  listChangeHis(id)
      .then((data) => {
        replaceActivities.value = data;
        for (var i = 0; i < replaceActivities.value.length; i++) {
          var record = replaceActivities.value[i];
          record.timeString =
              formatDate(
                  new Date(record.changeDateTime),
                  "yyyy-MM-dd HH:mm:ss"
              ) +
              " " +
              record.changerCode +
              " " +
              record.changerName;
        }
      })
      .catch(() => ElMessage.error("获取替换计划的记录失败!"));
};
// 替换下载
const downloadById = (fileId, fileName) => {
  downloadFile(fileId, fileName, "/mes");
};
// 替换表格替换
const handelReplace = (row) => {
  replaceDialog.value.childrenVisible = false;
  replaceDialogAddForm.value['newId'] = row.id;
  replaceDialogAddForm.value['newCode'] = row.code;
};
// 行调整参数
const lineAdjustDialog = ref({
  visible: false
});
const lineAdjustRefs = ref(null);
// 获取调整信息
const getChangeLineAdjustHis = (id) => {
  listChangeHis(id)
      .then((data) => {
        lineAdjustActivities.value = data;
        for (var i = 0; i < lineAdjustActivities.value.length; i++) {
          var record = lineAdjustActivities.value[i];
          record.timeString =
              formatDate(
                  new Date(record.changeDateTime),
                  "yyyy-MM-dd HH:mm:ss"
              ) +
              " " +
              record.changerCode +
              " " +
              record.changerName;
        }
      })
      .catch(() => ElMessage.error("获取替换计划的记录失败!"));
};
const lineAdjustDialogAddForm = ref({});
const lineAdjustActivities = ref([]);
const lineAdjust = (row) => {
  getChangeLineAdjustHis(row.id);

  lineAdjustDialogAddForm.value = {
    ...lineAdjustDialogAddForm.value,
    workOrderId: row.id,
    newPlanEnd: row.needEndDate,
    newPlanStart: row.needStartDate
  };
  lineAdjustDialog.value.visible = true;
};
// 行调整取消
const handlerLineAdjustAddCancel = () => {
  lineAdjustDialog.value.visible = false;
  lineAdjustRefs.value?.resetFields();
  lineAdjustDialogAddForm.value = {};
};
// 行调整保存
const handlerLineAdjustSubmit = () => {
  lineAdjustDialogAddForm.value.newPlanStart = formatDate(
      lineAdjustDialogAddForm.value.newPlanStart,
      "yyyy-MM-dd"
  );
  lineAdjustDialogAddForm.value.newPlanEnd = formatDate(
      lineAdjustDialogAddForm.value.newPlanEnd,
      "yyyy-MM-dd"
  );

  putWorkOrder(lineAdjustDialogAddForm.value)
      .then((res) => {
        ElMessage.success("修改计划成功!");
        handlerLineAdjustAddCancel();
        handleRefresh();
      });
};
// 规程参数
const regulationOption = ref({
  highlightCurrentRow: true,
  size: 'small',
  editBtn: false,
  delBtn: false,
  viewBtn: false,
  addBtn: false,
  height: "600",
  menuWidth: 180,
  column: [
    {
      label: "规程编号",
      prop: "targetCode",
      minWidth: 300,
      slot: true,
    },
    {
      label: "规程名称",
      prop: "targetName",
      minWidth: 300,
    },

    {
      label: "规程版本",
      prop: "targetRev",
      width: 80,
    },
    {
      label: "是否作废",
      prop: "obsoleteFlag",
      type: "switch",
      width: 80,
      align: 'center',
      slot: true,
      formatter: (val) => {
        return "true" == val.obsoleteFlag ? "是" : "否";
      },
    },
    {
      label: "添加日期",
      prop: "createTime",
      width: 145,
      type: "date",
      format: "YYYY-MM-DD",
    },
  ]
});
const regulationDialog = ref({
  visible: false
});
const regulationRow = ref({});
const SelectTechnologyEditRef = ref(null);
const SelectTechnologyAddRef = ref(null);
const regulationParams = computed(() => {
  return {
    workOrderId: regulationRow.value.id
  }
});
const regulationCrudRef = ref(null);
// 规程按钮点击事件
const regulationAddClickHandler = (row) => {
  regulationRow.value = row;
  regulationDialog.value.visible = true;
};
// 规程表格新增按钮
const onOpenWorksplus = () => {
  if (regulationRow.value.status == 'Obsoleted') {
    ElMessage.error("计划已经作废，不能再添加规程");
    return false;
  }
  let params = {
    type: "add",
    productCode: regulationRow.value.modelName,
    workOrderId: regulationRow.value.id,
  };
  SelectTechnologyAddRef.value.openDialog(params);
};
// 规程表格替换
const handelEditByrules = (row) => {
  let params = {
    workOrderId: row.id,
    targetId: row.targetId,
    productCode: regulationRow.value.modelName,
    type: "edit",
  };
  if (regulationRow.value.status == 'Obsoleted') {
    ElMessage.error("计划已经作废，不能再添加规程");
    return false;
  }
  if (regulationRow.value == 'true') {
    ElMessage.error("规程已经作废，不能替换");
    return false;
  }
  SelectTechnologyEditRef.value.openDialog(params);
};
// 规程表格作废
const handleEditByCancel = (row) => {
  confirm({msg: '确认作废这条规程吗?'}).then(() => {
    postCancle({id: row.id}).then((res) => {
      ElMessage.success("作废成功");
      handleRegulationRefresh();
    });
  })
};
// 规程替换刷新
const handleRegulationRefresh = () => {
  regulationCrudRef.value.getList();
};
</script>

<style lang="scss" scoped>

</style>
